<!--
author:        leishanfeng <1628316216@qq.com>
date:          2023-07-10 14:26:17
component:     index
Copyright © YourCompanyName All rights reserved
-->
<template>
  <div class="zbBox" :key="newid">
    <!-- <div class="append-box">
      <div>选择地址</div>
      <div class="append-img weizhi"></div>
    </div> -->
    <div class="MapBox">
      <div class="biaotiBox">
        <div>选择经纬度</div>
        <i
          class="el-icon-close"
          style="color: #4af6fc; cursor: pointer"
          @click="close"
        >
        </i>
      </div>
      <!-- 地址搜索 -->
      <div style="margin: 10px 20px 0 20px">
        <el-autocomplete
          v-model="address"
          :fetch-suggestions="querySearch"
          placeholder="输入关键词搜索"
          :trigger-on-focus="false"
          @select="handleSelect"
          width="540px"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
          <template #default="{ item }">
            <div class="suggestions-name">
              <span>{{ item.name }}</span>
            </div>
            <div class="suggestions-address">
              {{ item.address }}
            </div>
          </template>
        </el-autocomplete>
      </div>
      <div ref="mapRef" :id="newid" class="egismap"></div>
      <div
        style="
          font-size: 16px;
          font-family: MicrosoftYaHei;
          color: #ffffff;
          margin: 0 20px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          width: 1200px;
          text-align: left;
        "
      >
        <span class="text-primary" v-if="newAddress != ''">
          详细地址：{{ newAddress }}   经度：{{newCurrentPosition.lat}} 纬度：{{newCurrentPosition.lng}}
        </span>
        <span v-else class="text-danger">未获取到地址，请重新地图选点</span>
      </div>
      <div style="margin: 0 20px; text-align: right">
        <el-button
          @click="DialogVisibleNew"
          style="
            background: #1d5a8f;
            border-radius: 4px;
            border: 1px solid #7cadd8;
            font-size: 16px;
            font-family: MicrosoftYaHei;
            color: rgba(255, 255, 255, 0.9);
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import useService from './common/useService'
import useBase from './common/useBase'
const { newMarker, newImgMarker } = useBase()
const { searchKeyword, regeocode } = useService()
// wmts服务地址
const urlWMTS = 'http://120.52.31.31:590/service/api/egis/base/v1/wmts'
// 用户id
const clientId = '28524d8c65844630a3427270c9a16323'
// 用户密码
const clientSecret = '84bc17650bb04491aa8475b9cbe3d1c4'
// 创建地图
var egismap = new egis.carto.Map({
  defaultExtent: {
    center: [111.765617, 40.817498],
    maxZoom: 18,
    minZoom: 5,
    level: 11,
    extent: [-180, -90, 180, 90],
    projection: 'EPSG:4490'
  }
})
var resthttp = new egis.core.RestHttp({
  client_id: clientId,
  client_secret: clientSecret
})
egismap.globalToken(resthttp.getToken())
const currentPosition = {
  longitude: '',
  latitude: '',
  address: ''
}
const layers = {}
export default {
  name: 'EgisMap',
  props: {
    position: {
      type: Object,
      default: {
        longitude: '',
        latitude: '',
        address: ''
      }
    },
    isRefresh:{
      type:Number,
      default:""
    }
  },
  data() {
    return {
      newid: '',
      address: '',
      restaurants: [],
      mapDialogVisible: true,
      newAddress: '',
      zdaddress: '',
      newCurrentPosition:''
    }
  },
  watch: {
    isRefresh(newName, oldName) {
      console.log(newName, oldName,13333)
      let newid = 'map' + Date.now()
      this.newid = newid
      this.address = ''
      this.newAddress = ''
      this.$nextTick(() => {
        this.initMap(newid)
      })
      console.log(123)
    }
  },
  mounted() {
    let newid = 'map' + Date.now()
    this.newid = newid
    this.$nextTick(() => {
      this.initMap(newid)
    })
    console.log(123)
  },
  methods: {
    DialogVisibleNew() {
      this.mapDialogVisible = false
      this.$emit('getMapxq', '')
    },
    submitForm() {
      this.mapDialogVisible = false
      console.log(this.zdaddress)
      this.$emit('getMapxq', this.zdaddress)
    },
    close() {
      this.mapDialogVisible = false
      this.$emit('getMapxq', '')
    },
    initMap(newid) {
      // 初始化地图，传入要初始化的DOM对象的id
      egismap.init({ targetId: newid })
      // 创建影像底图图层
      // const imgBaseMap = new egis.carto.TileLayer({
      //   restHttp: resthttp,
      //   name: '影像底图',
      //   layers: 'img', // 图层名称
      //   matrix: 21, // 切图级别小于等于切图级别
      //   matrixSet: 'c', // 切图策略
      //   matrixPrefix: '', // 切图策略加冒号：
      //   format: 'tiles', // 图层格式
      //   projection: 'EPSG:4490', // 投影参考
      //   layerType: 1, // 图层类型
      //   tileType: 102, // 瓦片类型
      //   opacity: 1.0, // 透明度
      //   visible: true, // 是否显示
      //   crossOrigin: 'anonymous',
      //   style: 'default',
      //   extent: { minx: -180, miny: -90, maxx: 180, maxy: 90 },
      //   wrapX: true, // 是否展示循环图
      //   url: urlWMTS
      // })

      // // 创建影像行政区划图层
      // const divisionBaseMap = new egis.carto.TileLayer({
      //   restHttp: resthttp,
      //   name: '影像行政区划',
      //   layers: 'ibo', // 图层名称
      //   matrix: 21, // 切图级别小于等于切图级别
      //   matrixSet: 'c', // 切图策略
      //   matrixPrefix: '', // 切图策略加冒号：
      //   format: 'tiles', // 图层格式
      //   projection: 'EPSG:4490', // 投影参考
      //   layerType: 1, // 图层类型
      //   tileType: 102, // 瓦片类型
      //   opacity: 1.0, // 透明度
      //   visible: true, // 是否显示
      //   crossOrigin: 'anonymous',
      //   style: 'default',
      //   extent: { minx: -180, miny: -90, maxx: 180, maxy: 90 },
      //   wrapX: true, // 是否展示循环图
      //   url: urlWMTS
      // })

      // // 创建地图中文标注图层
      // const labelBaseMap = new egis.carto.TileLayer({
      //   restHttp: resthttp,
      //   name: '矢量注记',
      //   layers: 'cva', // 图层名称
      //   matrixSet: 'c', // 切图策略
      //   format: 'tiles', // 图层格式
      //   projection: 'EPSG:4490',
      //   extent: { minx: -180, miny: -90, maxx: 180, maxy: 90 },
      //   matrixPrefix: '',
      //   matrix: 21,
      //   tileType: 102, // 瓦片类型
      //   opacity: 1.0,
      //   visible: true,
      //   wrapX: true, // 是否展示循环图
      //   url: urlWMTS // 图层服务 url
      // })
// 创建 天地图矢量 瓦片图层
var tiandituvec = new egis.carto.TileLayer({
    restHttp: resthttp,
    name: "天地图矢量",
    layers: "vec", "//": "图层名称",
    matrix: 21, "//": "切图级别小于等于切图级别",
    matrixSet: "c", "//": "切图策略",
    matrixPrefix: "", "//": "切图策略加冒号：",
    format: "tiles", "//": "图层格式",
    projection: "EPSG:4490", "//": "投影参考",
    layerType: 1, "//": "图层类型",
    tileType: 102, "//": "瓦片类型",
    opacity: 1.0, "//": "透明度",
    visible: true, "//": "是否显示",
    crossOrigin: "anonymous",
    style: "default",
    extent: {minx: -180, miny: -90, maxx: 180, maxy: 90},
    wrapX: true, "//": "是否展示循环图",
    url: urlWMTS
    // "url": "http://t0.tianditu.gov.cn/vec_c/wmts?tk=4f62e1d82bd46e2ff470b291c2260156"
});

// 创建 天地图中文标注 瓦片图层
var tianditucta = new egis.carto.TileLayer({
    restHttp: resthttp,
    name: "天地图中文标注",
    layers: "cva",  // 图层名称
    matrixSet: "c",  // 切图策略
    format: "tiles",  // 图层格式
    projection: "EPSG:4490",
    extent: {minx: -180, miny: -90, maxx: 180, maxy: 90},
    matrixPrefix: "",
    matrix: 21,
    tileType: 102,  // 瓦片类型
    opacity: 1.0,
    visible: true,
    wrapX: true, "//": "是否展示循环图",
    url: urlWMTS  // 图层服务 url
    // "url": "http://t0.tianditu.gov.cn/cva_c/wmts?tk=4f62e1d82bd46e2ff470b291c2260156"
});
      // 将图层添加到地图
      // egismap.addLayer(imgBaseMap)
      egismap.addLayer(tiandituvec)
      egismap.addLayer(tianditucta)
      let that = this
      //       // 地图点击事件
      egismap.on(
        'click',
        (button, shift, screenX, screenY, mapX, mapY, handle) => {
          //   // console.log('click', button, shift, screenX, screenY, mapX, mapY, handle)
          that.mapClick({
            location: {
              lat: mapY,
              lng: mapX
            },
            screenX,
            screenY
          })
        }
      )
    },
    // 地图点击
    mapClick(e, tag = '') {
      console.log('click', e, egismap)
      let location = e.location
      currentPosition.lat = location.lat
      currentPosition.lng = location.lng
      this.newCurrentPosition={
        lat: location.lat,
        lng:location.lng
      }
      // // 获取详细地址
      this.getPosition(location)
      this.defaultMarker(currentPosition)
    },
    defaultMarker({ lat, lng }, panTo) {
      if (lat && lng) {
        this.createImgMarker({ lat, lng },this.newid)
        if (panTo) {
          egismap.setCenter({
            x: lng,
            y: lat
          })
        }
      }
    },
    // 获取详细地址
    getPosition(location) {
      let that = this
      regeocode(location).then(res => {
        console.log('regeocode', res)
        that.zdaddress = res
        // 详细地址
        // currentPosition.address = res.formatted_address
        currentPosition.cityName = res.address_component.city
        currentPosition.regionName = res.address_component.district
        currentPosition.regionCode = res.address_component.adcode
        that.newAddress = res.formatted_address
      })
    },

    // 创建点标绘
    createMarker({ lat, lng }, layerName) {
      let elementlayer = null
      if (layerName && layers[layerName]) {
        elementlayer = layers[layerName]
        elementlayer.clear()
      } else {
        //创建标绘图层
        elementlayer = new egis.carto.ElementLayer({
          id: layerName,
          name: '标记图层'
        })
        //标绘图层添加到地图上
        egismap.addLayer(elementlayer)
        if (layerName) layers[layerName] = elementlayer
      }

      //构造一个空的点元素对象
      var pointElement = newMarker({ lat, lng })
      elementlayer.add(pointElement)
      // console.log(elementlayer, pointElement)

      return pointElement
    },
    // 创建点标绘
    createImgMarker({ lat, lng }, layerName) {
      let elementlayer = null
      console.log(lat, lng, layerName)
      if (layerName && layers[layerName]) {
        elementlayer = layers[layerName]
        elementlayer.clear()
      } else {
        //创建标绘图层
        elementlayer = new egis.carto.ElementLayer({
          id: layerName,
          name: '标记图层'
        })
        //标绘图层添加到地图上
        console.log(lat, lng, layerName, egismap)
        egismap.addLayer(elementlayer)
        if (layerName) layers[layerName] = elementlayer
      }

      //构造一个空的点元素对象
      var pointElement = newImgMarker({ lat, lng })
      elementlayer.add(pointElement)
      console.log(elementlayer, pointElement, '112233')

      return pointElement
    },
    querySearch(value, cb) {
      console.log(value)
      let timer = null
      if (value) {
        clearTimeout(timer)
        timer = setTimeout(() => {
          searchKeyword(value).then(res => {
            console.log('res', res)
            this.restaurants = res.pois || []
            cb(res.pois || [])
          })
        }, 300)
      } else {
        this.restaurants = []
        cb([])
      }
    },

    // 地址选择
    handleSelect(data) {
      console.log('select', data)
      let currentPosition = {
        latitude: data.location.y,
        longitude: data.location.x,
        address: data.address
      }
      // 获取详细地址
      regeocode({ lat: data.location.y, lng: data.location.x }).then(res => {
        // 详细地址
        currentPosition.cityName = res.address_component.city
        currentPosition.regionName = res.address_component.district
        currentPosition.regionCode = res.address_component.adcode
      })
      this.address = data.address
      currentPosition.address = data.address
      currentPosition.lat = data.location.y
      currentPosition.lng = data.location.x
       this.newCurrentPosition={
        lat:data.location.y.toFixed(8),
        lng:data.location.x.toFixed(8)
       }
      this.getPosition(currentPosition)
      this.defaultMarker(currentPosition, true)
    }
  }
}
</script>

<style lang="scss" scoped>
.egismap {
  width: calc(100% - 40px);
  height: 70%;
  margin: 20px 20px 0 20px;
  :deep(.cesium-viewer) {
    width: 100%;
    height: 100%;
  }
}

.append-box {
  width: 114px;
  height: 30px;
  background: rgba(124, 173, 216, 0.2);
  border-radius: 0px 4px 4px 0px;
  border: 1px solid #7cadd8;
  position: relative;
  left: -2px;
  z-index: 20;
  cursor: pointer;
  font-size: 16px;
  font-family: MicrosoftYaHei;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.append-img {
  width: 14px;
  height: 14px;
  margin-left: 10px;
  background: url('~@/assets/TeamAdministrator/location.png') no-repeat;
}
.mapBtn {
  width: 114px;
  height: 100%;
  background: rgba(124, 173, 216, 0.2);
  border-radius: 0px 4px 4px 0px;
  border: 1px solid #7cadd8;
  position: relative;
  left: -2px;
  z-index: 20;
}
.el-autocomplete {
  display: block;
}
.el-autocomplete-suggestion {
  border: none;
}
.el-scrollbar {
  font-size: 12px;
  background: rgba(6, 50, 88, 0.9);
  .el-dropdown-menu__item:not(.is-disabled):focus {
    background-color: rgba(0, 160, 255, 0.2);
  }
  .el-scrollbar__view {
    font-size: 12px;
    .suggestions-name {
      font-size: 12px;
      color: #cbe7ff;
      line-height: normal;
    }
    li {
      height: 34px;
      line-height: 34px;
    }
    .suggestions-address {
      font-size: 12px;
      line-height: normal;
      color: #999;
    }
    li:hover {
      background: rgba(0, 160, 255, 0.2) !important;
      .suggestions-name {
        color: #4af6fc;
      }
      .suggestions-address {
        color: #cbe7ff;
      }
    }
  }
}
.el-input {
}
.el-popper {
  overflow: auto;
}
.MapBox {
  margin: 110px 20px 20px 20px;
  width: 100%;
  height: calc(100% - 150px);
  // z-index: 9999;
  background: rgba(6, 50, 88, 0.9);
  box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}
.zbBox {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  // position: relative;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.5);

  // left:-50px;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
}
.biaotiBox {
  font-size: 18px;
  font-family: MicrosoftYaHei;
  color: rgba(255, 255, 255, 0.9);
  height: 24px;
  margin: 20px 20px 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.text-primary {
  color: #fff;
}
.text-danger {
  color: #ff5151;
}
</style>
